import request from "../../utils/http";
import { Address } from "../../utils/type";
import { anyObj, enter, wxBack } from "../../utils/util";

// pages/chooseAddress/chooseAddress.ts
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		query: <anyObj>{},
		addressId: 0,
		addressList: <Address[]>[]
	},

	editAddress(e: WechatMiniprogram.CustomEvent) {
		enter({
			pageName: 'saveAddress',
			query: {
				addressId: e.currentTarget.dataset.id
			}
		});
	},

	onChange(e: WechatMiniprogram.CustomEvent) {
		const addressId = e.detail.value || e.currentTarget.dataset.id;
		this.setData({
			addressId
		});
		if (this.data.query.type === 'view') return;
		
		wx.setStorageSync("CHOOSE_ADDRESS", JSON.stringify(this.data.addressList.find(address => address.id == addressId)));
		wxBack({});
	},

	async getAddressList() {
		try {
			const addressList = await request({
				url: '/api/customers/address/getAll',
				method: 'GET',
				errToast: true,
				showLoading: {title: '正在获取所有地址...'}
			});
			this.setData({addressList});
		} catch (error) {
			
		}
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad(query: anyObj) {
		this.setData({
			query,
			addressId: Number(query.addressId) || 0
		});
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow() {
		this.getAddressList();
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() {

	}
})